﻿using System;
using System.Windows.Forms;
using roster.UI;
using roster.Domain;

namespace roster
{
    public class Program
    {
        [STAThread]
        public static void Main()
        {
            SetExceptionHandling();

            var runningContext = new ApplicationContext();
            
            RaidFileRegistrar.Instance.RegisterRaidFileType("lua", new SavedVarsRaidFileReader());

            RosterController rosterController = GetRosterController();
            rosterController.Closed += delegate { runningContext.ExitThread(); };
            rosterController.Show();

            Application.Run(runningContext);
        }

        private static void SetExceptionHandling()
        {
            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        }

        private static RosterController GetRosterController()
        {
            var playerController = new PlayerController(new PlayerView());
            var raidController = new RaidController(new RaidView());
            var playerSelectionController = new PlayerSelectionController(new PlayerSelectionView());
            var createRosterController = new CreateRosterController(new CreateRosterView());
            var rosterController = new RosterController(new RosterView(), playerController, raidController,
                                                        playerSelectionController, createRosterController);
            return rosterController;
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            PrintException((Exception) e.ExceptionObject);
        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            PrintException(e.Exception);
        }

        private static void PrintException(Exception exception)
        {
            MessageBox.Show(exception.Message, "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
    }
}